import time,re
import pandas as pd
import redis
import pickle
import logging
import hashlib
import configparser
import datetime
from sqlalchemy import create_engine, DateTime, String
import pymysql
import traceback

import warnings

# 忽略所有警告
warnings.filterwarnings('ignore')


pymysql.install_as_MySQLdb()


log_format = "%(asctime)s - %(levelname)s - %(process)d - %(filename)s:%(lineno)d - %(message)s"
date_format = "%Y-%m-%d %H:%M:%S"  # 精确到秒
logging.basicConfig(level=logging.DEBUG, format=log_format, datefmt=date_format)

# 初始化配置解析器
config = configparser.ConfigParser()

import os
current_dir = os.path.dirname(os.path.abspath(__file__))
config.read(current_dir+'/config.ini')


# 获取Redis的配置信息
redis_host = config.get('Redis', 'host')
# redis_host = "192.168.249.10"

redis_port = config.getint('Redis', 'port')
redis_db = config.getint('Redis', 'db')
redis_password = config.get('Redis', 'password')
r = redis.Redis(host=redis_host, port=redis_port, db=redis_db, password=redis_password)

mysql_port = config.getint('mysql', 'port')
mysql_host = config.get('mysql', 'host')
mysql_db = config.get('mysql', 'db')
import urllib.parse
mysql_password = urllib.parse.quote(config.get('mysql', 'password'))
mysql_user = config.get('mysql', 'user')
db_url = f'mysql://{mysql_user}:{mysql_password}@{mysql_host}:{mysql_port}/{mysql_db}'
engine = create_engine(db_url,pool_size=20,max_overflow=20,pool_recycle=60)


def add_remark(row):
    # 判断股票代码开头和对应条件
    if ((row['股票代码'].startswith('30') or row['股票代码'].startswith('68')) and row['change'] > 19.9):
        if row['hs_change'] > 3:
            return '20cm换手涨停'
        elif row['hs_change'] < 1:
            return '20cm一字板'
    elif ((row['股票代码'].startswith('00') or row['股票代码'].startswith('60')) and row['change'] > 9.88):
        if row['hs_change'] > 1:
            return '10cm换手涨停'
        elif row['hs_change'] < 1:
            return '10cm一字板'
    # 如果都不满足上述条件，则返回空值或其他默认值
    return ''

def get_brand_and_concept_rank(query_date,stock_name,stock_fupan_df,real_stock_info_tdx,real_market_brand_index_tdx,real_market_concept_index_tdx):


    stock_df =stock_fupan_df.query(f'股票简称 == "{stock_name}"')

    brand_df = real_market_brand_index_tdx

    stock_result={}
    stock_result["name"] = stock_name
    #获取标的行业信息
    brand_name = stock_df["所属同花顺行业"].values[0]
    brand_df = brand_df.query(f'name == "{brand_name.split('-')[-1]}"')
    brand_df["concept_type"] = "行业"


    #获取标的概念信息
    s = stock_df["所属概念"].values[0]
    concpet_list = s.split(';')
    concpet_df = real_market_concept_index_tdx
    concpet_df = concpet_df[concpet_df['concept_name'].isin(concpet_list)]
    concpet_df["concept_type"] = "概念"
    concpet_df = pd.concat([brand_df,concpet_df])
    concpet_df = concpet_df.sort_values(by="avr_change",ascending=False)

    try:
        logging.info(f"最强概念：{concpet_df['name'].values[0]}")
    except Exception as e:
        tb_info = traceback.format_exc()
        # 将异常信息和 traceback 信息一起记录
        logging.info(f"An error occurred: {e}\nTraceback info:\n{tb_info}")
        logging.info(concpet_df)
        logging.info(real_stock_info_tdx["timestamp"].values[0])


    stock_result["concept_name"] = concpet_df['concept_name'].values[0]
    stock_result["concept_change"] = concpet_df['avr_change'].values[0]
    stock_result["concept_change_hs"] = concpet_df['avr_change_hs'].values[0]
    stock_result["concept_zt_count"] = concpet_df['zt_count'].values[0]
    stock_result["concept_rps"] = concpet_df['avr_change_rank'].values[0]
    stock_result["concept_rps_hs"] = concpet_df['avr_change_hs_rank'].values[0]
    stock_result["concept_type"] = concpet_df['concept_type'].values[0]

    df = pd.merge(stock_fupan_df,real_stock_info_tdx,how="inner",left_on="股票代码",right_on="code")

    if stock_result["concept_type"]=="行业":
        df = df[df['所属同花顺行业'].str.contains(stock_result["concept_name"], regex=False)]
    else:
        df = df[df['所属概念'].str.contains(stock_result["concept_name"], regex=False)]


    df = df.sort_values(by="change",ascending=False)
    df["hs_change"] = round(100*(df["price"]-df["open"])/df["open"],2)
    df = df[["股票代码","股票简称","连续涨停天数","change","hs_change"]]

    # # 应用函数并创建新列“备注”
    df['remark'] = df.apply(add_remark, axis=1)
    # 检查是否存在换手涨停
    no_turnover_limit = not any(df['remark'].str.contains('换手涨停'))


    df['hs_change_rank'] = df['hs_change'].rank(ascending=False, method='min')

    # 选股逻辑
    # 添加涨幅类型
    df['类型'] = df['股票代码'].apply(lambda x: '20cm' if x.startswith(('30', '68')) else '10cm')
    df['排名'] = df['change'].rank(method='dense', ascending=False)


    cdf = df[df['股票简称']==stock_name]
    stock_type = cdf["类型"].values[0]
    stock_rank = cdf["排名"].values[0]

    stock_result["concept_rank"] = stock_rank

    remark = cdf["remark"].values[0]

    stock_result["suggestion"] ="不买"

    if stock_type=="20cm" and remark!='20cm一字板':
        if stock_rank==1:
            s = "板块20cm领涨，买"
            stock_result["suggestion"] = s

    if stock_type=="10cm" and remark!='10cm一字板':
        if stock_rank==1:
            s = "板块10cm领涨，买"
            stock_result["suggestion"] = s

        else:
            tdf = df.copy()

            tdf = tdf[~tdf['remark'].str.contains("20cm换手涨停", na=False)]
            tdf = tdf[~tdf['remark'].str.contains("一字板", na=False)]
            tdf = tdf[~tdf['类型'].str.contains("20cm", na=False)]
            tdf['排名'] = tdf['change'].rank(method='dense', ascending=False)
            ccdf = tdf[tdf['股票简称'] == stock_name]


            cc_stock_rank = ccdf["排名"].values[0]

            if cc_stock_rank==1:
                s = "板块10cm换手领涨，买"
                stock_result["suggestion"] = s



    return stock_result



if __name__ == "__main__":
    # logging.info("个股行业与概念涨幅排名分析开始监听:")
    query_date = datetime.datetime.now().strftime('%Y%m%d')
    query_date = '20240429'
    print(get_brand_and_concept_rank(query_date,'莱宝高科'))










